
<script setup lang="ts">
import { ref, reactive, nextTick, markRaw } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getGasEchartsDataApi } from '@/api/gas'
import fixTime from '@/utils/fixTime'
import { formatTime } from '@/utils/common'
// props
const props = defineProps({
  gasData: {
    type: Object,
    default: null
  },
  gasType: {
    type: Number,
    default: 2
  }
})

// 定义变量
// 控制弹框显隐
const dialogTableVisible = ref(false)

// 气体数量
const gasNumber = ref(2)
// 图表数据源
const resultData:any = ref([])
// echart实例
const myEcharts = echarts
const chart = ref()
// x轴
let xAxisData: any = []
// 气体具体数据
let coSeriesData:any = []
let so2SeriesData:any = []
let ch4SeriesData:any = []
let smokeSeriesData:any = []
let dustSeriesData: any = []
// echarts数据源和设置
const option = {
  xAxis: {
    type: 'category',
    data: [ '' ]
  },
  yAxis: {
    type: 'value'
  },
  // 显示图例
  legend: {
    data: [ '一氧化碳', '二氧化硫', '甲烷', '烟气', '粉尘' ]
  },
  tooltip: {
    trigger: 'axis'
  },
  grid: {
    left: '5%',
    right: '3%',
    containLabel: true
  },
  series: [ {} ]
}

const nowTime = new Date()
// 筛选时间
const time = ref([ new Date(nowTime.getTime() - 24 * 60 * 60 * 1000), nowTime ])
// 时间间隔
const timeInterval = ref('1')
// 时间单位
const timeUnit = ref('hours')
const unitOptions = ref([
  {
    value: 'seconds',
    label: '秒'
  },
  {
    value: 'minutes',
    label: '分钟'
  },
  {
    value: 'hours',
    label: '小时'
  },
  {
    value: 'day',
    label: '天'
  },
  {
    value: 'week',
    label: '星期'
  },
  {
    value: 'month',
    label: '月'
  }
])
// 图标数据变量定义
let coData:any = ref([])
let ch4Data:any = ref([])
let smokeData:any = ref([])
let so2Data:any = ref([])
let dustData: any = ref([])

const yardCode = ref(0)
const codeList = ref('')

// 定义方法
// 展示弹框
const showGasHistoryDialog = async (type:number, yard:number, code:string) => {
  gasNumber.value = type
  yardCode.value = yard
  codeList.value = code
  let data = {
    CreateStartTime: fixTime(time.value[0]),
    CreateEndTime: fixTime(time.value[1]),
    BarYardCode: yard,
    BarSectionCode: yard, 
    code: code
  }
  
  let res = await getGasEchartsDataApi(data)
  console.log('气体历史数据---->', res)
  // if (res.code === -1) {
  //   ElMessage({
  //     // message: `${res.message}`,
  //     message: '网络请求中断获取数据错误！',
  //     type: 'warning'
  //   })
  //   return
  // }
  
  console.log('气体历史数据---->', res)
  resultData.value = res
  for (let key in res) {
    switch (key.split('_')[3]) {
    case 'CO':
      coData.value = res[key]
      console.log('一氧化碳历史数据---->', coData.value, res[key])
      break
    case 'CH4':
      ch4Data.value = res[key]
      console.log('甲烷历史数据---->', ch4Data.value, res[key])
      break
    case 'FOG':
      dustData.value = res[key]
      console.log('粉尘历史数据---->', dustData.value, res[key])
      break
    case 'SMOKE':
      smokeData.value = res[key]
      console.log('烟感历史数据---->', smokeData.value, res[key])
      break
    case 'SO2':
      so2Data.value = res[key]
      console.log('氧气历史数据---->', so2Data.value, res[key])
      break
    }
  }
  // res.forEach((item:any) => {
  // console.log('气体历史数据---->', item.key)
  //   switch (item.key) {
  //   case 'CO':
  //     coData.value = item.safetyDetailStatisticsDtos
  //     console.log('一氧化碳历史数据---->', coData.value, item.safetyDetailStatisticsDtos)
  //     break
  //   case 'CH4':
  //     ch4Data.value = item.safetyDetailStatisticsDtos
  //     console.log('甲烷历史数据---->', ch4Data.value, item.safetyDetailStatisticsDtos)
  //     break
  //   case 'dust':
  //     dustData.value = item.safetyDetailStatisticsDtos
  //     console.log('粉尘历史数据---->', dustData.value, item.safetyDetailStatisticsDtos)
  //     break
  //   case 'smoke':
  //     smokeData.value = item.safetyDetailStatisticsDtos
  //     console.log('烟感历史数据---->', smokeData.value, item.safetyDetailStatisticsDtos)
  //     break
  //   case 'SO2':
  //     so2Data.value = item.safetyDetailStatisticsDtos
  //     console.log('氧气历史数据---->', so2Data.value, item.safetyDetailStatisticsDtos)
  //     break
  //   }
  // })
  echartDataFix()
  dialogTableVisible.value = true
}

// 初始化Echarts图表
const initChart = () => {
  let series = [
    {
      name: '一氧化碳',
      data: coSeriesData,
      type: 'line',
      smooth: true
    },
    {
      name: '甲烷',
      data: ch4SeriesData,
      type: 'line',
      smooth: true
    },
    {
      name: '烟气',
      data: smokeSeriesData,
      type: 'line',
      smooth: true
    },
    {
      name: '粉尘',
      data: dustSeriesData,
      type: 'line',
      smooth: true
    },
    {
      name: '二氧化硫',
      data: so2SeriesData,
      type: 'line',
      smooth: true
    }
  ]
  option.series = series
  // }
  option.xAxis.data = xAxisData
  console.log('echarts的Option----->', option)
  if (chart.value) {
    chart.value.dispose()
  }
  nextTick(() => {
    chart.value = markRaw(myEcharts.init(document.getElementById('container')))
    chart.value.setOption(option)
  })
}
// 销毁Echarts
const destroyEchart = () => {
  time.value = [ new Date(nowTime.getTime() - 24 * 60 * 60 * 1000), nowTime ]
  timeInterval.value = '1'
  timeUnit.value = 'hours'
  chart.value.dispose()
}

// 查询设备信息
const queryDevice = async () => {
  if (!time.value[0] || !time.value[1] || !timeInterval.value || !timeUnit.value) {
    ElMessage({
      message: '请完整输入查询条件！！！',
      type: 'warning'
    })
    return
  }
  let data = {
    CreateStartTime: fixTime(time.value[0]),
    CreateEndTime: fixTime(time.value[1]),
    BarYardCode: yardCode.value,
    BarSectionCode: yardCode.value, 
    code: codeList.value
  }
  // console.log('气体历史数据---->', data)
  // fixXAxis(time.value)
  let res = await getGasEchartsDataApi(data)
  resultData.value = res
  for (let key in res) {
    switch (key.split('_')[3]) {
    case 'CO':
      coData.value = res[key]
      // console.log('一氧化碳历史数据---->', coData.value, res[key])
      break
    case 'CH4':
      ch4Data.value = res[key]
      // console.log('甲烷历史数据---->', ch4Data.value, res[key])
      break
    case 'dust':
      dustData.value = res[key]
      // console.log('粉尘历史数据---->', dustData.value, res[key])
      break
    case 'smoke':
      smokeData.value = res[key]
      // console.log('烟感历史数据---->', smokeData.value, res[key])
      break
    case 'SO2':
      so2Data.value = res[key]
      // console.log('氧气历史数据---->', so2Data.value, res[key])
      break
    }
  }
  echartDataFix()
}

// 清除查询数据
const clearQueryData = () => {
  timeInterval.value = ''
  time.value[0] = new Date(nowTime.getTime() - 24 * 60 * 60 * 1000)
  time.value[1] = new Date()
  timeUnit.value = ''
}

// 确认按钮
const confirm = () => {
  time.value = [ new Date(nowTime.getTime() - 24 * 60 * 60 * 1000), nowTime ]
  timeInterval.value = '1'
  timeUnit.value = 'hours'
  dialogTableVisible.value = false

}

// 毫秒数转日期
const millisecondsToDate = (time:number) => {
  let datetime = new Date(time)
  let year = datetime.getFullYear()
  let month = datetime.getMonth()
  let date = datetime.getDate()
  let hour = datetime.getHours()
  let minute = datetime.getMinutes()
  let second = datetime.getSeconds()

  let result1 = year +
    '-' +
    ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
    '-' +
    ((date + 1) < 10 ? '0' + date : date) +
    ' ' +
    ((hour + 1) < 10 ? '0' + hour : hour) +
    ':' +
    ((minute + 1) < 10 ? '0' + minute : minute) +
    ':' +
    ((second + 1) < 10 ? '0' + second : second)

  let result2 = year +
    '-' +
    ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
    '-' +
    ((date + 1) < 10 ? '0' + date : date)

  let result = {
    hasTime: result1,
    withoutTime: result2
  }
  return result
}

// 数据清洗 
const echartDataFix = () => {
  xAxisData = []
  coSeriesData = []
  so2SeriesData = []
  ch4SeriesData = []
  smokeSeriesData = []
  dustSeriesData = []
  // console.log('清洗前的数据----->', xAxisData, coSeriesData, so2SeriesData, ch4SeriesData, smokeSeriesData, dustSeriesData)
  coData.value.forEach((item:any, index:any) => {
    // console.log('清洗中的数据----->', item)
    xAxisData.unshift(formatTime(item.creationTime))
    if (item.value === null) {
      coSeriesData.push(0)
    } else {
      coSeriesData.push(item.value)
    }
  })
  so2Data.value.forEach((item: any, index: any) => {
    if (item.value === null) {
      so2SeriesData.push(0)
    } else {
      so2SeriesData.push(item.value)
    }
  })
  ch4Data.value.forEach((item: any, index: any) => {
    if (item.value === null) {
      ch4SeriesData.push(0)
    } else {
      ch4SeriesData.push(item.value)
    }
  })
  smokeData.value.forEach((item: any, index: any) => {
    if (item.value === null) {
      smokeSeriesData.push(0)
    } else {
      smokeSeriesData.push(item.value)
    }
    
  })
  dustData.value.forEach((item: any, index: any) => {
    if (item.value === null) {
      dustSeriesData.push(0)
    } else {
      dustSeriesData.push(item.value)
    }
  })
  // console.log('清洗后的数据----->', xAxisData, coSeriesData, so2SeriesData, ch4SeriesData, smokeSeriesData, dustSeriesData)
  initChart()
}

// 暴露出去的函数
defineExpose({
  showGasHistoryDialog
})
</script>
<template>
  <el-dialog
    v-model="dialogTableVisible"
    modal-append-to-body
    class="gas-dialog"
    @open="initChart"
    @close="destroyEchart"
  >
    <template #header>
      <div class="gas-header-box">
        <div class="title">
          气体历史曲线
        </div>
        <!-- <div class="position-name">
          气体位置{{ props.gasData.name }}
        </div> -->
      </div>
    </template>
    <div class="query-criteria-box">
      <div style="width: 450px;">
        <el-date-picker
          v-model="time"
          class="gas-time"
          type="datetimerange"
          style="width: 100%;"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          teleported
        />
      </div>
      <div class="btn-box">
        <div
          class="search-btn"
          @click="queryDevice"
        >
          查询
        </div>
        <div class="icon-divider" />
        <div
          class="clear-btn"
          @click="clearQueryData"
        >
          清空筛选条件
        </div>
      </div>
    </div>
    <div id="container" />
    <div
      class="confirm-btn"
      @click="confirm"
    />
  </el-dialog>
</template>

<style lang="scss" scoped>
.two-item-box {
  display: flex;
  width: 68px;
  height: 40px;
  margin-top: 16px;
  margin-left: 6px;
  background: #f8fafd;
  border: 1px solid rgba($color: #000, $alpha: 0%);
  border-radius: 54px;
  box-shadow: 0 4px 8px 0 rgb(166 184 208 / 40%);
  opacity: 1;
  >div {
    width: 24px;
    height: 24px;
    margin-top: 8px;
    margin-left: 8px;
    line-height: 24px;
    text-align: center;
    background: linear-gradient(180deg, #54aafe 0%, #4482ed 100%);
    border-radius: 24px;
    box-shadow: 0 2px 4px 0 #bbd2ff;
    opacity: 1;
  }
  .o2-box {
    margin-left: 4px;
  }
}
.two-item-box:hover {
  cursor: pointer;
}
.first-son {
  margin-left: 50px;
}
.second-son {
  margin-left: 1192px;
}
.btn-box {
  display: flex;
  margin-left: 30px;

  /* border: 1px solid red; */
  >div {
    width: 44px;
    height: 20px;
    margin-top: 6px;
    font-weight: 600;
    font-size: 14px;
    font-family: PingFang, sans-serif;
    line-height: 20px;
    text-align: center;
    background-clip: text;
  }
  .search-btn {
    color: #2191ff;
  }
  .search-btn:hover {
    cursor: pointer;
  }
  .clear-btn {
    width: 95px;
  }
  .clear-btn:hover {
    cursor: pointer;
  }
}
.icon-divider {
  width: 0 !important;
  height: 12px !important;
  margin-top: 10px !important;
  border: 1px solid #a9aeb8 !important;
}
#container {
  width: 970px;
  height: 550px;
}
</style>
<style lang="scss">
.query-criteria-box {
  display: flex;
  justify-content: space-between;
  .gas-time {
    width: 100px;

    /* border: 1px solid red; */
  }
  .gas-interval {
    width: 200px;
    margin-left: 20px;

    /* border: 1px solid red; */
  }
  .gas-unit {
    width: 150px;
    margin-left: 20px;

    /* border: 1px solid red; */
  }
}
</style>
